from django.db.models import F
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from ..models import Document
from ..serializers import (
    DocumentSerializer,
    DocumentDetailSerializer,
    DocumentListSerializer,
    DocumentSearchSerializer
)

class DocumentViewSet(viewsets.ReadOnlyModelViewSet):
    """文档视图集"""
    queryset = Document.objects.filter(is_published=True)
    serializer_class = DocumentSerializer
    lookup_field = 'slug'

    def get_serializer_class(self):
        """根据不同的操作返回对应的序列化器"""
        if self.action == 'list':
            return DocumentListSerializer
        if self.action == 'retrieve':
            return DocumentDetailSerializer
        if self.action == 'search':
            return DocumentSearchSerializer
        if self.action in ['latest', 'recommended', 'popular']:
            return DocumentListSerializer
        return self.serializer_class

    def get_queryset(self):
        queryset = super().get_queryset()
        category = self.request.query_params.get('category')
        if category:
            queryset = queryset.filter(category__slug=category)
        return queryset.filter(is_published=True)

    @action(detail=True, methods=['post'])
    def views(self, request, slug=None):
        """增加浏览量"""
        document = self.get_object()
        document.views = F('views') + 1
        document.save()
        document.refresh_from_db()
        return Response({
            'code': 0,
            'message': 'success',
            'data': {
                'views': document.views
            }
        })

    @action(detail=False, methods=['get'])
    def latest(self, request):
        """获取最新文档"""
        limit = int(request.query_params.get('limit', 10))
        documents = self.get_queryset().order_by('-updated_at')[:limit]
        serializer = self.get_serializer(documents, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        })

    @action(detail=False, methods=['get'])
    def recommended(self, request):
        """获取推荐文档"""
        limit = int(request.query_params.get('limit', 10))
        documents = self.get_queryset().filter(is_recommended=True).order_by('-updated_at')[:limit]
        serializer = self.get_serializer(documents, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        })

    @action(detail=False, methods=['get'])
    def popular(self, request):
        """获取热门文档"""
        limit = int(request.query_params.get('limit', 10))
        documents = self.get_queryset().filter(is_popular=True).order_by('-views')[:limit]
        serializer = self.get_serializer(documents, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': serializer.data
        })

    @action(detail=False, methods=['get'])
    def search(self, request):
        """搜索文档"""
        query = request.query_params.get('q', '')
        if not query:
            return Response({
                'code': 0,
                'message': 'success',
                'data': {
                    'count': 0,
                    'next': None,
                    'previous': None,
                    'results': []
                }
            })

        documents = self.get_queryset().filter(title__icontains=query)
        page = self.paginate_queryset(documents)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response({
                'code': 0,
                'message': 'success',
                'data': serializer.data
            })

        serializer = self.get_serializer(documents, many=True)
        return Response({
            'code': 0,
            'message': 'success',
            'data': {
                'count': documents.count(),
                'next': None,
                'previous': None,
                'results': serializer.data
            }
        })

    def list(self, request, *args, **kwargs):
        response = super().list(request, *args, **kwargs)
        return Response({
            'code': 0,
            'message': 'success',
            'data': response.data
        })

    def retrieve(self, request, *args, **kwargs):
        response = super().retrieve(request, *args, **kwargs)
        return Response({
            'code': 0,
            'message': 'success',
            'data': response.data
        }) 